package org.pentaho.di.core.database.util;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;

public class CustomDriverManager {

    public Enumeration<Driver> getDrivers(ClassLoader classLoader) {
        Thread.currentThread().setContextClassLoader(classLoader);
        Enumeration<Driver> drivers = DriverManager.getDrivers();
        return drivers;
    }

    public static Connection getConnection(String url, java.util.Properties info, Enumeration<Driver> drivers, ClassLoader classLoader) throws SQLException {
        Thread.currentThread().setContextClassLoader(classLoader);
        if(url == null) {
            throw new SQLException("url连接不能为空", "08001");
        }

        // Walk through the loaded registeredDrivers attempting to make a connection.
        // Remember the first exception that gets raised so we can reraise it.
        SQLException reason = null;

        while(drivers.hasMoreElements()){
            try {
                Driver driver = drivers.nextElement();
                Connection con = driver.connect(url, info);
                if (con != null) {
                    // Success!
                    return (con);
                }
            } catch (SQLException ex) {
                if (reason == null) {
                    reason = ex;
                }
            }
        }

        // if we got here nobody could connect.
        if (reason != null)    {
            throw reason;
        }

        throw new SQLException("未找到合适的驱动, "+ url, "08001");
    }

}
